from time import sleep

from infection_monkey.island_api_client import IIslandAPIClient, IslandAPIRequestLimitExceededError

from .i_agent_otp_provider import IAgentOTPProvider


class IslandAPIAgentOTPProvider(IAgentOTPProvider):
    def __init__(self, island_api_client: IIslandAPIClient):
        self._island_api_client = island_api_client

    def get_otp(self) -> str:
        # Note: Using too large of a delay here will cause the exploiter
        # threads/processes to hang
        for _ in range(6):
            try:
                return self._island_api_client.get_otp()
            except IslandAPIRequestLimitExceededError:
                sleep(0.5)
                continue
            except Exception as err:
                raise RuntimeError(err)
        raise RuntimeError("Failed to get OTP: Too many requests.")
